﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Text.RegularExpressions;
using System.IO;
using System.Net.Sockets;

namespace SS
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// ID
        /// </summary>
        private string aid;
        public string AdressVoteSend2 = "/plus/count.php?view=yes&ipp=Y&typecs=clicknum&aid={0}&mid=347";
        
        private bool isStop = false;
        HttpClient webClientQu;
        /// <summary>
        /// 是否执行连接
        /// </summary>
        private bool isConnect = false;
        List<Thread> threadList;
        /// <summary>
        /// 地址信息
        /// </summary>
        private VoteUrl voteUrl;
        VoteCount voteCount;
        private string strConnect;
        DateTime beginTime;
        private int secondTime = 10;
        private int threadNum = 10;

        //顾土104026 //范恩宇104018  ss 104032
        private void Form1_Load(object sender, EventArgs e)
        {
           // this.KeyPreview = true;
            voteUrl = new VoteUrl(
                adressVoteShow: "http://www.s1979.com/yule/zt/201101/vote_daren.html",
                adressRoot: "www.s1979.com",
                adressVoteSend: "http://www.s1979.com/plus/count.php?view=yes&ipp=Y&typecs=clicknum&aid={0}&mid=347");
            this.aid = "104026";
            this.txtAid.Text = this.aid;
            FormatUrl();
            this.timer2.Interval = 1000 * 60 * 20;
            this.threadList = new List<Thread>();
            this.btnStart.Enabled = true;
            voteCount = new VoteCount();
            webClientQu = new HttpClient(new Uri(voteUrl.AdressVoteShow));
            SetVisible(false);
            this.cboProxy.Checked = true;
            Thread.CurrentThread.Name = "z_t";
            
        }
        /// <summary>
        /// 设置 设置ID文本，和文本框 的显示与隐藏
        /// </summary>
        /// <param name="b"></param>
        private void SetVisible(bool b)
        {
            SetVoteIdVisible(b);
        }

        // 开始 或结束 后 设置 状态
        private void SetVisibleOfBeginEnd(bool b)
        {
            ChangeState(b);
            this.timer1.Enabled = !b;
        }

        //格式化 url地址
        /// <summary>
        /// 格式化 url地址
        /// </summary>
        private void FormatUrl()
        {
            this.aid = this.txtAid.Text;
            this.Text = "2010_" + aid;
            voteUrl.AdressVoteSend = "http://www.s1979.com/plus/count.php?view=yes&ipp=Y&typecs=clicknum&aid={0}&mid=347";
            AdressVoteSend2 = "/plus/count.php?view=yes&ipp=Y&typecs=clicknum&aid={0}&mid=347";
            voteUrl.AdressVoteSend = string.Format(voteUrl.AdressVoteSend, aid);
            this.AdressVoteSend2 = string.Format(this.AdressVoteSend2, aid);
            
        }

        //点击开始
        private void btnStart_Click(object sender, EventArgs e)
        {
            PrintThreadState();
            isStop = false;
            //this.threadList.Clear();
            if (this.txtAid.Text.Trim()!="")
            {
                FormatUrl();
            }
            SetVisible(false);
            strConnect = this.txtConnect.Text.Trim();
            bool isInt = Int32.TryParse(this.txtTime.Text.Trim(), out secondTime);
            if (!isInt || secondTime < 0)
            {
                secondTime = 0;
            }
            secondTime = 0;
            this.txtTime.Text = secondTime.ToString();
            beginTime = DateTime.Now;
            
            isInt = Int32.TryParse(this.txtThreadNum.Text.Trim(), out threadNum);
            if (threadNum == 0)
            {
                threadNum = 12;
            }
            threadEndCount = 0;
            this.txtThreadNum.Text = threadNum.ToString();
            SetVisibleOfBeginEnd(false);
            GetNum();
            Thread tt = new Thread(new ThreadStart(NewThreadStart));
            tt.Start();

        }
        /// <summary>
        /// 创建 并启动线程
        /// </summary>
        public void NewThreadStart()
        {
            for (int i = 0; i < threadNum; i++)
            {
                Thread th = new Thread(new ThreadStart(Start));
                th.IsBackground = true;
                th.Name = "子线程名称" + i;
                th.Start();
                this.threadList.Add(th);
            }
        }
        
        /// <summary>
        /// 开始
        /// </summary>
        private void Start()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("GET " + AdressVoteSend2 + " HTTP/1.1" + Environment.NewLine);
            sb.Append("Host: www.s1979.com" + Environment.NewLine);
            sb.Append("Referer: " + voteUrl.AdressVoteShow + "" + Environment.NewLine);
            sb.Append("Accept: */*" + Environment.NewLine);
            sb.Append("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.634.0 Safari/534.16" + Environment.NewLine);
            sb.Append("Accept-Language: zh-CN,zh;q=0.8" + Environment.NewLine);
            sb.Append("Accept-Encoding: gzip,deflate,sdch" + Environment.NewLine);
            sb.Append("Accept-Charset: GBK,utf-8;q=0.7,*;q=0.3" + Environment.NewLine);
            sb.Append("Connection: Close" + Environment.NewLine);
            sb.Append(Environment.NewLine);
            string sendData = sb.ToString();
            int port = 80;
            //创建终结点EndPoint
            IPAddress ipe = null;
            if (this.cboProxy.Checked)
            {
                ipe = IPAddress.Parse("113.108.99.133");//未使用
                port = 80;
            }
            else
            {
                //ipe = IPAddress.Parse("59.51.24.226");//使用
                ipe = IPAddress.Parse("59.51.72.50");
                port = 80;
            }
            IPEndPoint ipendPoint = new IPEndPoint(ipe, 80);
            //IPEndPoint ipe = new IPEndPoint(ipS1979, port);//把ip和端口转化为IPEndpoint实例
            while (!isStop)
            {
                try
                {

                    voteCount.NumberCount++;
                    Thread.Sleep(200);
                    if (voteCount.NumberCount % 200 == 0)
                    {
                        voteCount.NumberCount++;
                        this.SetText("aa");
                        
                    }
                    continue;
                    /////创建socket并连接到服务器
                    Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建Socket
                    c.Connect(ipendPoint);//连接到服务器
                    //Socket c= GetSocket(ipeProxy, "113.108.99.133", 80,sendData);
                    ///向服务器发送信息
                    byte[] bs = Encoding.Default.GetBytes(sendData);//把字符串编码为字节
                    c.Send(bs, bs.Length, 0);//发送信息
                    ///接受从服务器返回的信息
                    StringBuilder recvStr = new StringBuilder();
                    byte[] recvBytes = new byte[1024];
                    int bytes;
                    do
                    {
                        bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
                        recvStr.Append(Encoding.Default.GetString(recvBytes, 0, bytes));
                    } while (bytes > 0);
                    //禁用上次的发送和接受 
                    c.Shutdown(SocketShutdown.Both);
                    ///一定记着用完socket后要关闭
                    c.Close();
                    string voteResult = recvStr.ToString();
                    string num = "";
                    if (this.cboProxy.Checked)
                    {
                        num = new MatchData(Environment.NewLine, Environment.NewLine,
                      new MatchData(Environment.NewLine + Environment.NewLine,
                          Environment.NewLine + Environment.NewLine, voteResult).Match()).Match();//正常连接下取值
                        voteCount.NumberCount++;
                        if (voteCount.NumberCount % 200 == 0)
                        {
                            voteCount.NumberCount++;
                            this.SetText("ok_z." + num);
                        }
                    }
                    else
                    {
                        num = new MatchData(Environment.NewLine + Environment.NewLine, "", voteResult).MatchToEnd();
                        voteCount.NumberCount++;
                        if (voteCount.NumberCount % 200 == 0)
                        {
                            this.SetText("ok_p." + num);
                        }
                    }

                    if (secondTime != 0)
                    {
                        this.SetText("程序在休息" + secondTime + "s");
                        Thread.Sleep(secondTime * 1000);
                    }
                    if (rdoIPLoop.Checked)
                    {
                        //Connect();
                    }
                }
                catch (Exception e)
                {
                    voteCount.FailureCount++;
                    int threadId = Thread.CurrentThread.ManagedThreadId;
                    this.SetText("error:<" + threadId + ">" + e.Message);
                    //Thread.Sleep(5000);
                }
            }
            PrintEnd();
        }

        private int threadEndCount = 0;
        /// <summary>
        /// 打印结束
        /// </summary>
        private void PrintEnd()
        {

            lock (this)
            {
                if (threadEndCount==0)
                {
                    this.SetText("正在结束.....");
                }
                threadEndCount++;
                this.SetText(Thread.CurrentThread.Name+":在退出..."+threadEndCount);
                if (threadEndCount >= threadNum)
                {
                    this.SetText("<"+threadEndCount+">结束投票。 有效票数:...");
                    this.SetVisibleOfBeginEnd(true);
                    Callback callback = new Callback(PrintThreadState);
                    this.Invoke(callback);
                    //this.threadList.Clear();
                }
            }
        }

        public void PrintThreadState()
        {
            List<Thread> list = this.threadList;
            if (list!=null)
            {
                foreach (var thread in list)
                {
                    this.SetText(thread.Name + "状态是" + thread.ThreadState + ";IsAlive:" + thread.IsAlive);
                    //thread.Abort();
                    //((thread.ThreadState & (ThreadState.Stopped | ThreadState.Unstarted)) == 0)
                    if(thread.ThreadState == ThreadState.Running)
                    {
                        this.SetText("运行中");
                    }
                     
                }
            }
        
        }

        private void btnStop_Click(object sender, EventArgs e)
        {

            if (this.txtThreadNum.Text.Trim()=="setaid")
            {
                SetVisible(true);
            }
            else
            {
                isStop = true;
                if (this.threadList.Count>0)
                {
                    this.btnStop.Enabled = false;
                }
            }
        }
        //获取 总票数
        /// <summary>
        /// 获取 总票数
        /// </summary>
        private void GetNum()
        {
            WebClient web = new WebClient();
            try
            {
                string result = web.DownloadString(voteUrl.AdressVoteSend);
                int i = 0;
                bool b = Int32.TryParse(result, out i);
                if (b)
                {
                    voteCount.SuccessCount++;
                    this.SetText("票数 is " + i);
                    SetSumNum(i.ToString());
                    
                }
                else
                {
                    this.SetText("失败额." + result);
                }
            }
            catch (Exception)
            {
                this.SetText("获取总票数错误。");
            }
        }

        TimeSpan timeSpan;
        #region 计时器
        //计时器
        private void timer1_Tick(object sender, EventArgs e)
        {
            timeSpan = DateTime.Now.Subtract(beginTime);
            lblTime.Text = timeSpan.ToString();

        }
        #endregion
 
        //刷新
        private void llblF5_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            GetNum();
        }
        //过某段时间 记录 日志
        private void timer2_Tick(object sender, EventArgs e)
        {
            GetNum();
            Log();
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            GetNum();
            Log();
        }

         
    }
}
